"use strict";

function init() {
    var vm = new Vue({
        el: "#app",
        data: {
            title: "添加",
            type: 0,
            id: 0,
            backUrl: '../main/main.html',

            formData: {
                account:"",
                id: '',
                password: '',
                salt: '',
                tags: '',
                userId: ''
            },
           
            hideLoadingToast: true,
            errorAlert: {
                hideErrorAlert: true,
                errMsg : "未知错误"
            }
        },
        methods: {
            initForm() {
                if (this.type == 1) {
                    keyService.get({
                        "id": this.id
                    }, function (data) {
                        this.formData = data;
                    }, function (errMsg) {
                        _this.errorAlert.errMsg = errMsg;
                        _this.errorAlert.hideErrorAlert = false
                    })
                } else {
                    var currUser = mm.getStorage($C.currUser);
                    this.formData.userId = currUser.id;
                }
            },
            back() {
                mm.go(this.backUrl)
            },
            validForm() {
                if(!this.formData.password) {
                    this.errorAlert.errMsg = "密码值不能为空";
                    this.errorAlert.hideErrorAlert = false
                    return false;
                }
                if(!this.formData.tags) {
                    this.errorAlert.errMsg = "标签不能为空";
                    this.errorAlert.hideErrorAlert = false
                    return false;
                }
                return true;
            },
            submit() {
                if(!this.validForm()) return;
                var _this = this;
                this.hideLoadingToast = false
                keyService.add(this.formData, function(data) {
                    _this.hideLoadingToast = true
                    _this.success()
                }, function(errMsg) {
                    _this.hideLoadingToast = true
                    _this.errorAlert.errMsg = errMsg;
                    _this.errorAlert.hideErrorAlert = false
                });
            },
            success() {
                mm.go(this.backUrl)
            },
            hideAlert() {
                this.errorAlert.hideErrorAlert = true;
            }
        },
        created() {
            this.type = mm.getUrlParam("type")
            if(this.type == 1) {
                this.id = mm.getUrlParam("id")
                this.title = ""
            }
             // 获取从哪个页面跳转过来的页面，如果没有，则跳转到登录页面
            this.backUrl = mm.getUrlParam("fromUrl") || "../main/main.html";
            
            this.initForm()
        }
    })
}

init();